#!/usr/bin/env python

import gobject, gtk
import re
import os
from blend import mxf
from blend import excepts
import time
import urllib

class emoticons:

   def __init__(self,temp,cache):
      self.temp = temp;
      self.cache = cache;

   def getCustomEmoticons(self,conv,message):
      pattern = r'<customEmote code="\.\{[a-zA-Z0-9]*\}"/>';
      pattern = re.compile(pattern);
      matches = pattern.findall(message);

      for i in range(0,len(matches)):
         shortcut = matches[i].replace('<customEmote code="','').replace('"/>','');
         gobject.timeout_add(150,self.downloadCustomEmoticon,conv,shortcut);


   def downloadCustomEmoticon(self,conv,shortcut):
      code = shortcut[2:-1];
      filename = code + "_15.mxf";
      imagename = code + "_15" + ".png";

      fileLocation = self.downloadEmoticon(filename,code);
      # There was some problem with the emote file. Most likely there was no such
      # emoticon or something.
      #return False;
         
      imageLocation = os.path.join(self.temp,imagename);
      
      if not self.createEmoticonImage(fileLocation,imageLocation):
         return False;

      buf = conv.view.get_buffer();
      mark = buf.get_mark('emote:%s' % shortcut);
      iter = buf.get_iter_at_mark(mark);

      # Remove the shortcut text
      try:
         shortcutTextStartIter, shortcutTextEndIter = iter.forward_search(shortcut,gtk.TEXT_SEARCH_TEXT_ONLY);
         buf.delete(shortcutTextStartIter,shortcutTextEndIter);
      except:
         pass;

      pixbuf = gtk.gdk.pixbuf_new_from_file(imageLocation);
      iter = buf.get_iter_at_mark(mark); # We have to get the iter because of the above modification
      buf.insert_pixbuf(iter,pixbuf);

      # Finally, we can remove the mark
      buf.delete_mark(mark);

      return False;


   def downloadEmoticon(self,filename,code):
      c = self._exists(filename);
      if c == False:
         return self._download(code,filename);
      else:
         return c;

   def createEmoticon(self,file):
      filename = self._exists(file);
      if filename == False:
         return False;

      shortcut = file[:-7];
      sF = shortcut + ".png";
      loc = os.path.join(self.temp,sF);
      
      d = open(filename,'rb');
      data = d.read();
      d.close();
      mxfFile = mxf.mxfReader(data);
      mxfStuff = mxfFile.parse();
      try:
         d = open(loc,'wb');
         d.write(mxfStuff.data);
         d.close();
         return (shortcut,mxfStuff.name,loc);
      except AttributeError, excepts.MalformedMXFData:   # There is no data in the mxf file :o
         return False;              



   def createEmoticonImage(self,filename,imagename):
      d = open(filename,'rb');
      data = d.read();
      d.close();
      mxfFile = mxf.mxfReader(data);
      mxfStuff = mxfFile.parse();
      try:
         d = open(imagename,'wb');
         d.write(mxfStuff.data);
         d.close();
         return True;
      except AttributeError, excepts.MalformedMXFData:   # There is no data in the mxf file :o
         return False;              


   # This needs to retrieve the file in the background
   # otherwise it will hang the displaying of text.. which would be bad
   def replaceEmoticons(self,matchobj):
      shortcut = matchobj.group(0);
      code = shortcut[2:-1];
      filename = code + "_15.mxf";
      imagename = code + "_15" + ".png";

      if os.path.exists(os.path.join(self.temp,imagename)):
         return '<img src="%s" alt="%s" />' % (os.path.join(self.temp,imagename),shortcut);
      if os.path.exists(os.path.join(self.temp,filename)):
         self.createEmoticonImage(os.path.join(self.temp,filename),os.path.join(self.temp,imagename));
         return '<img src="%s" alt="%s" />' % (os.path.join(self.temp,imagename),shortcut);
      elif os.path.exists(os.path.join('cached',filename)):
         self.createEmoticonImage(os.path.join('cached',filename),os.path.join(self.temp,imagename));
         return '<img src="%s" alt="%s" />' % (os.path.join(self.temp,imagename),shortcut);

      # We have to download it. :/ So we return the code
      # The html view widget has been modified to support the
      # customEmote tag. It will turn it into a TextView tag
      # that we can search for later.. once we've downloaded the
      # emote.
      return '<customEmote code="%s"/>' % shortcut; 


   def findCustomEmoticons(self,message):
      pattern = r"(\.\{[a-zA-Z0-9]*\})";
      pattern = re.compile(pattern);
      return pattern.sub(self.replaceEmoticons,message,re.MULTILINE);

   def _download(self,shortcut,filename,size=15):
      ttime = int(time.time());
      request = "type=emo&mlh=%i&sc=%s&ts=%i" % (size,shortcut,ttime);
      res = urllib.FancyURLopener();
      d = res.open("http://www.mxit.com/res/?" + request);
      data = d.read();
      d.close();
      res.close();
      
      return self._store(data,filename);

   def _store(self,data,filename):
      if self.cache == True:
         f = open(os.path.join('cached',filename),'wb');
         f.write(data);
         f.close();
         return os.path.join('cached',filename);
      else:
         f = open(os.path.join(self.temp,filename),'wb');
         f.write(data);
         f.close();
         return os.path.join(self.temp,filename);

   def _exists(self,filename):
      if os.path.exists(os.path.join('cached',filename)):
         return os.path.join('cached',filename)
      elif os.path.exists(os.path.join(self.temp,filename)):
         return os.path.join(self.temp,filename)
      else:
         return False;